package com.atguigu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 向域对象共享数据
 * 1.通过 ModelAndView 向请求域共享数据
 * 使用 ModelAndView 时，可以使用 Model 功能向请求域共享数据
 * 使用 View 功能设置逻辑视图，但是控制器一定要将 ModelAndView 作为方法的返回值
 * 2.使用 Model 向请求域中共享数据
 * 3.使用 ModelMap 向请求域中共享数据
 * 4.使用 map 向请求域中共享数据
 * 5.Model 和 ModelMap 的关系
 * public interface Model{}
 * public class ModelMap extends LinkedHashMap<String, Object> {}
 * public class ExtendedModelMap extends ModelMap implements Model {}
 * public class BindingAwareModelMap extends ExtendedModelMap {}
 */
@Controller
public class TestScopeController {
    @RequestMapping("/test/mav")
    public ModelAndView testMAV(){
        /**
         * ModelAndView 包含 model 和 view
         * model：向请求域中共享数据
         * view:设置逻辑视图实现页面跳转
         */
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("testRequestScope","hello,modelAndView");
        modelAndView.setViewName("success");
        return modelAndView;
    }
    @RequestMapping("/test/model")
    public String testModel(Model model){
        System.out.println(model.getClass().getName());
        model.addAttribute("testRequestScope","hello, model");
        return "success";
    }
    @RequestMapping("/test/modelmap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testRequestScope","hello, modelmap");
        return "success";
    }
    @RequestMapping("/test/map")
    public String testMap(Map<String,Object> map){
        map.put("testRequestScope","hello ,map ");
        return "success";
    }
    @RequestMapping("/test/session")
    public String testSession(HttpSession session){
        session.setAttribute("testRequestScope","hello,session");
        return "success";
    }
    @RequestMapping("/test/application")
    public String testApplication(HttpSession session){
        ServletContext application = session.getServletContext();
        application.setAttribute("testRequestScope","hello,application");
        return "success";
    }
}
